package com.example.framework.web.core.filter;

import com.example.framework.common.util.servlet.ServletUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author yuzhenxin
 * @date 2023-07-07 23:05
 */
@Slf4j
public class CacheRequestBodyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("---------- CacheRequestBodyFilter 放行，url: {} ----------", request.getRequestURL());
        filterChain.doFilter(new CacheRequestBodyWrapper(request), response);
        // doFilter后不能再执行代码，否则抛出 getOutputStream() has already been called for this response
    }

    @Override
    protected boolean shouldNotFilter(@NotNull HttpServletRequest request) {
        // 只处理 json 请求内容
        // 如果请求是GET，那么request.getContentType()为null；一般POST请求为json请求，才需要缓存请求体
        return !ServletUtils.isJsonRequest(request);
    }
}
